import AsyncStorage from "@react-native-async-storage/async-storage";
import React, { useReducer, useEffect } from "react";
import queryApi from "../../api/query";

const companySupplierContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "initCompanySupplier":
      return action.payload;
    case "addCompanySupplier":
      return [...state, action.payload];
    case "deleteCompanySupplier":
      return state.filter((supplier) => supplier._id !== action.payload._id);
    default:
      return state;
  }
};

export const CompanySupplierProvider = ({ children }) => {
  const [companySupplier, dispatch] = useReducer(dataReducer, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const token = await AsyncStorage.getItem("token");
        if (!token) {
          console.log("请求userId出错");
        }
        const result = await queryApi.get("/user/companysupplier", {
          headers: { Authorization: token },
        });
        if (result.data.members) {
          dispatch({
            type: "initCompanySupplier",
            payload: result.data.members,
          });
        }
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, []);

  const deleteCompanySupplier = async (deleteSuppiler) => {
    if (deleteSuppiler) {
      dispatch({
        type: "deleteCompanySupplier",
        payload: deleteSuppiler,
      });
    } else {
      console.log("删除员工为空");
    }
  };

  const addCompanySupplier = async (addSuppiler) => {
    if (addSuppiler) {
      let haveSupplier = false;
      companySupplier.forEach((supplier) => {
        if (String(supplier._id) == String(addSuppiler._id)) {
          haveSupplier = true;
        }
      });
      if (!haveSupplier) {
        dispatch({
          type: "addCompanySupplier",
          payload: addSuppiler,
        });
      }
    } else {
      console.log("添加员工为空");
    }
  };

  return (
    <companySupplierContext.Provider
      value={{
        companySupplier: companySupplier,
        addCompanySupplier,
        deleteCompanySupplier,
      }}
    >
      {children}
    </companySupplierContext.Provider>
  );
};

export default companySupplierContext;
